package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.dto.AlertDataPageDto;
import com.zzyl.nursing.dto.ChangeAlertDataDto;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.sql.ast.statement.SQLIfStatement;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.dialect.auto.C3P0AutoDialect;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.AlertDataPageDto;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-28
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

//    /**
//     * 查询报警数据列表
//     *
//     * @param dto 报警数据
//     * @return 报警数据
//     */
//    @Override
//    public List<AlertData> selectAlertDataList(AlertData dto) {
//        List<AlertData> alertData = alertDataMapper.selectAlertDataList(dto);
//
//        alertData.forEach(alertdata -> {
//            //管理员登录
//            Long userId = alertdata.getUserId();
//            if(userId==1){
//
//            }else {
//                //不是管理员
//                //判断是否有对应的数据，有的话返回
//            }
//
//        });
//        return alertData;
//    public List<AlertData> selectAlertDataList(AlertDataPageDto dto)
//    {
//        //取用户id
//        Long userId = SecurityUtils.getUserId();
//        List<AlertData> alertDataList = this.lambdaQuery().eq(StrUtil.isNotBlank(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
//                .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
//                .eq(userId != null, AlertData::getUserId, userId)
//                .between((dto.getStartTime() != null && dto.getEndTime() != null), AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime())
//                .list();
//        return alertDataList;
//    }

    /**
     * 新增报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData)
    {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     * 
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData)
    {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     * 
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 分页查询老人报警数据
     *
     * @param dto
     * @return
     */
    @Override
    public Page<AlertData> selectAlertData(AlertDataPageDto dto) {
        Long userId = SecurityUtils.getUserId();//获取当前用户ID
        return   this.lambdaQuery()
                    .eq(StrUtil.isNotBlank(dto.getDeviceName()) && !dto.getDeviceName().trim().isEmpty(), AlertData::getDeviceName, dto.getDeviceName())
                    .eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                    .between(dto.getStartTime() != null&& dto.getEndTime() != null,
                            AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime())
                    .eq(AlertData::getUserId,userId)//根据userID展示对应的用户页面
                    .page(new Page<>(dto.getPageNum(), dto.getPageSize()));

    }





    /**
     * 处理设备报警数据
     *
     * @param dto
     */

    @Autowired
    private ISysUserService sysUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeAlertData(ChangeAlertDataDto dto) {
        //字符串转为时间
        String processingTime = dto.getProcessingTime();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        LocalDateTime localDateTime = LocalDateTime.parse(processingTime, dateTimeFormatter);
        //查询操作人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = sysUserService.lambdaQuery().select(SysUser::getNickName).eq(SysUser::getUserId,loginUser.getUserId()).one();

        //根据id查询设备数据
        AlertData alertData = alertDataMapper.selectById(dto.getId());
        //处理人执行,有处理原因
        this.lambdaUpdate()
                .set(AlertData::getProcessingResult,dto.getProcessingResult())
                .set(AlertData::getProcessingTime,localDateTime)
                .set(AlertData::getProcessorName,sysUser.getNickName())
                .set(AlertData::getStatus, Constants.STATUS_ONE)
                //根据创建时间与iotId联合查询,取保设备数据唯一
                .eq(AlertData::getCreateTime,alertData.getCreateTime())
                .eq(AlertData::getId,dto.getId())
                .update();
        //关联者处理,只更新状态,更新处理人,根据创建时间跟IotId执行
        this.lambdaUpdate()
                .set(AlertData::getStatus,Constants.STATUS_ONE)
                .set(AlertData::getProcessingTime,localDateTime)
                .set(AlertData::getProcessorName,sysUser.getNickName())
                .eq(AlertData::getCreateTime,alertData.getCreateTime())
                .eq(AlertData::getIotId,alertData.getIotId())
                .update();
    }
}
